// component/ui/z-collapses/z-collapses.js
import {
  _toArray
} from '../common/utils';
const path = '../z-collapse/z-collapse'

Component({
  relations: {
    [path]: {
      type: 'descendant',
      linked: function (target) {},
      linkChanged: function (target) {},
      unlinked: function (target) {}
    }
  },
  /**
   * 组件的配置
   */
  options: {
    styleIsolation: 'isolated',
    pureDataPattern: /^_/,
  },
  /**
   * 组件的属性列表
   */
  properties: {
    value: {
      type: [Array, String, Number],
      observer: 'updateExpanded',
    },
    accordion: {
      type: Boolean,
      value: false,
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    current: []
  },

  /**
   * 组件的生命周期
   */
  lifetimes: {
    created() {
      Object.defineProperty(this, 'children', {
        get: () => this.getRelationNodes(path) || [],
      });
    },
    attached() {},
    detached() {},
  },

  /**
   * 页面的生命周期
   */
  pageLifetimes: {
    show: function () {},
    hide: function () {},
    resize: function (size) {}
  },

  /**
   * 组件的方法列表
   */
  methods: {
    updateExpanded(val) {
      this.setData({
        current: _toArray(val),
      });
      this.children.forEach((child) => {
        child.updateExpanded();
      });
    },
    switch (name, isExpand) {
      const {
        accordion,
        value
      } = this.data;
      if (!accordion) {
        name = isExpand ?
          (value || []).concat(name) :
          (value || []).filter((activeName) => activeName !== name);
      } else {
        name = isExpand ? name : '';
      }
      this.triggerEvent('change', name);
    },
  }
})